package com.sduept.nwld.dataserver.rest.fault;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sduept.nwld.dataserver.manager.fault.SignalChangeManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ProtectActionCache {

	@Autowired
	private SignalChangeManager signalChangeManager;
	
	/**
	 * 查询一个变电站下的保护动作时间
	 * @param stationId
	 * @return
	 */
	public String getProtectActionByStationId(String stationId){

		JSONArray jsa = new JSONArray();
		
		List<?> signalList = signalChangeManager.findProtectByStation(stationId);
		JSONArray jsnArr;//faulttime、point数组
		Map<String, String> deviceMap = new HashMap<String, String>();//deviceId和mProtectName组织键值对
		Map<String, String> primDevMap = new HashMap<String, String>();//deviceId和mPrimdevType键值对
		Map<String, JSONArray> timeMap = new HashMap<String, JSONArray>();//faultTime和point
		for(Object obj : signalList){//deviceId和mProtectName组织键值对
			Object[] objs = (Object[]) obj;
			deviceMap.put(objs[4].toString(), objs[1].toString());
			
			if(objs[2].toString().contains("XL")){
				primDevMap.put(objs[4].toString(), "线路保护");
			}else if(objs[2].toString().contains("BYQ")){
				primDevMap.put(objs[4].toString(), "变压器保护");
			}else if(objs[2].toString().contains("MX")){
				primDevMap.put(objs[4].toString(), "母线保护");
			}else{
				primDevMap.put(objs[4].toString(), "开关保护");
			}

			String[] strArr = objs[3].toString().split(",");//point时间点
			jsnArr = new JSONArray();
			jsnArr.add(objs[0]);
			jsnArr.add(Double.valueOf(strArr[0])/1000);
			JSONArray jsnArr2 = timeMap.get(objs[4].toString());
			if(jsnArr2 == null){//deviceId不同
				jsnArr2 = new JSONArray();
				jsnArr2.add(jsnArr);
				timeMap.put(objs[4].toString(), jsnArr2);
			}else{//deviceId相同，直接追加
				jsnArr2.add(jsnArr);
			}
		}
		
		Map<String, JSONArray> typeMap = new HashMap<String, JSONArray>();//type和time
		for(String key : timeMap.keySet()){//组织类型、时间的键值对

			JSONObject jsObj;
			JSONArray jsArr = typeMap.get(primDevMap.get(key));
			if(jsArr == null){//type不同时新建arr
				jsArr = new JSONArray();
//				jsArr.add(timeMap.get(key));
				jsObj = new JSONObject();
				jsObj.put("time", timeMap.get(key));
				jsObj.put("name", deviceMap.get(key));
				jsArr.add(jsObj);
				typeMap.put(primDevMap.get(key), jsArr);
			}else{//type相同
				jsObj = new JSONObject();
				jsObj.put("time", timeMap.get(key));
				jsObj.put("name", deviceMap.get(key));
				jsArr.add(jsObj);
			}
		}
		
		for(String key : typeMap.keySet()){
			JSONObject jso = new JSONObject();
			jso.put("value", typeMap.get(key));
			jso.put("type", key);
			jsa.add(jso);
		}
		
		return jsa.toJSONString();
	}
	
	
	
}
